<template>
  <div>
    <!-- 总部订货单导入-->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @onCollapse="collapseHandle" :labelWidth="110" @resetChange="resetChange"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTables
        ref="table"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :onSyncTableData="tableChange"
        columnsRef="zjHeadquartersOrder"
        :pageSizesArray="[20, 40, 100, 200, 500]"
        :onRowSelectChange="selectChangeHandle"
        :onColumnsChange="columns => (this.columns = columns)"
      >
        <template slot="controls" slot-scope="props">
          <multiuse-button size="small" type="primary" @click="addHandle(1)" icon="el-icon-plus">新 增</multiuse-button>
          <multiuse-button size="small" type="primary" @click="addHandle(2)">导 出</multiuse-button>
          <multiuse-button size="small" type="primary" @click="addHandle(3)">导 入</multiuse-button>
          <multiuse-button size="small" type="primary" @click="addHandle(4)" :disabled="isOpen">批量提交</multiuse-button>
          <multiuse-button size="small" type="primary" @click="addHandle(5)" :disabled="isOpen">批量删除</multiuse-button>
        </template>
      </FilterTables>
    </Spin>

    <Drawer :visible.sync="addVisible" :title="'订单信息'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="80%">
      <addModel @close="addcloseHandler" />
    </Drawer>
    <BaseDialog :visible.sync="issearch" :title="'经销商查询'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <ownerSeacher :rowData="formData" @close="ownerclose" />
    </BaseDialog>
    <Drawer :visible.sync="emmitVisible" :title="'订单信息'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="80%">
      <emitModel :rowData="formData" @close="emitcloseHandler" />
    </Drawer>
    <Drawer :visible.sync="detailVisible" :title="'订单信息'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="80%">
      <detailModel :rowData="formData" @close="detailCloseHandler" />
    </Drawer>
    <BaseDialog :visible.sync="visible" :closable="false" :title="'导入'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <importFiles @close="importcloseHandler" />
    </BaseDialog>
  </div>
</template>
<script>
import { getList, exportList, getNotPage, deleteOrderById, subOrderById, getDeptList, getOfficeList, subOrderBatch, exporturl,deleteOrderByIds } from '@/api/omSale/OrderManagement/HeadquartersOrder/index.js';
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils';
import ownerSeacher from './ownerSeacher';
import emitModel from './emitModel';
import detailModel from './detailModel';
import addModel from './addModel';
import importFiles from './importFiles';
export default {
  name: 'HeadquartersOrder',
  data() {
    this.BaseTable = null;
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: getList,
      fetchParams: {
        isLead: 10041001,
        searchType: 1,
        xhrAbort: false
      },
      exportLoading: false,
      formData: {},
      emmitVisible: false,
      issearch: false,
      addVisible: false,
      detailVisible: false,
      visible: false,
      isOpen: true
    };
  },
  mixins: [dictionary],
  components: {
    ownerSeacher,
    emitModel,
    detailModel,
    addModel,
    importFiles
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.getDeptList();
  },
  methods: {
    tableChange(val) {
      val.map(x => {
        x.buildRebateTotalAmountLocalShow = x.buildRebateTotalAmountStart + x.buildRebateTotalAmount;
      });
    },
    createdFrom() {
      return [
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '请选择',
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.seacherFun(1)}></el-button>
              </div>
            );
          }
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入'
        },
        {
          type: 'RANGE_DATE',
          label: '创建日期',
          fieldName: 'startDate|endDate',
          placeholder: '请选择',
          initialValue: [],
          dateType: 'exactdaterange'
        },
        {
          type: 'SELECT',
          label: '订单类型',
          fieldName: 'orderType',
          placeholder: '请选择',
          itemList: [
            { text: '常规订单', value: 60061001 },
            { text: '特殊订单', value: 60061005 },
            { text: '大客户订单', value: 60061009 }
          ],
          change: p => {
            if (p) {
              this.topFilterList.find(x => x.fieldName == 'orderDetailType').itemList = [];
              this.topFilterList.find(x => x.fieldName == 'orderDetailType').initialValue = '';
              this.getNotPage(p);
            } else {
              this.topFilterList.find(x => x.fieldName == 'orderDetailType').itemList = [];
              this.topFilterList.find(x => x.fieldName == 'orderDetailType').initialValue = '';
            }
          }
        },
        {
          type: 'SELECT',
          label: '订单类型细分',
          fieldName: 'orderDetailType',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '订单状态',
          fieldName: 'orderStatus',
          placeholder: '请选择',
          itemList: [
            { text: '待提交', value: 60431001 },
            { text: '审批驳回', value: 60431002 }
          ]
        },
        {
          type: 'INPUT',
          label: '订货单编号',
          fieldName: 'orderNo',
          placeholder: '请输入'
        },
        {
          type: 'SELECT',
          label: '事业部',
          fieldName: 'deptId',
          placeholder: '请选择',
          itemList: [],
          change: p => {
            if (p) {
              this.getOfficeList(p);
            } else {
              this.topFilterList.map(x => {
                if (x.fieldName == 'officeId') {
                  x.initialValue = '';
                  x.itemList = [];
                }
              });
            }
          }
        },
        {
          type: 'SELECT',
          label: '办事处',
          fieldName: 'officeId',
          placeholder: '请选择',
          itemList: []
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 200,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 1)} disabled={props.row.orderStatus != 60431001 && props.row.orderStatus != 60431002}>
                  编辑
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 2)}>
                  详情
                </multiuse-button>
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 3)} disabled={props.row.orderStatus != 60431001 && props.row.orderStatus != 60431002}>
                  提报
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 4)} disabled={props.row.orderStatus != 60431001 && props.row.orderStatus != 60431002}>
                  删除
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '事业部',
          dataIndex: 'deptName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '办事处',
          dataIndex: 'officeName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '订货单编号',
          dataIndex: 'orderNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'center',
          width: 200
        },
        {
          title: '订单类型',
          dataIndex: 'orderType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [
            { text: '常规订单', value: 60061001 },
            { text: '特殊订单', value: 60061005 }
          ],
          render: p => {
            return <span>{this.createDictText(p.row.orderType, '6006')}</span>;
          }
        },
        {
          title: '订单细分类型',
          dataIndex: 'orderDetailName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '订单状态',
          dataIndex: 'orderStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [
            { text: '待提交', value: 60431001 },
            { text: '审批驳回', value: 60431002 }
          ],
          render: p => {
            return <span>{this.createDictText(p.row.orderStatus, '6043')}</span>;
          }
        },
        {
          title: '订单年月',
          dataIndex: 'orderYearMonth',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '运输方式',
          dataIndex: 'transportType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('6004'),
          render: p => {
            return <span>{this.createDictText(p.row.transportType, '6004')}</span>;
          }
        },
        {
          title: '提报数量',
          dataIndex: 'orderTotalNum',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '订单总金额',
          dataIndex: 'beforeTotalAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '折扣总金额',
          dataIndex: 'discountTotalAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '返利使用总金额',
          dataIndex: 'rebateTotalAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '单车返利总金额',
          dataIndex: 'singleRebateTotalAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '建店返利总金额',
          dataIndex: 'buildRebateTotalAmountLocalShow',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '实付总金额',
          dataIndex: 'realPayTotalAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '创建人',
          dataIndex: 'createdName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '创建日期',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    async getDeptList() {
      let res = await getDeptList({ orgType: 15061005 });
      let arr = res.data.map(x => ({ text: x.orgName, value: x.orgId }));
      this.topFilterList.find(x => x.fieldName == 'deptId').itemList = arr;
    },
    async getOfficeList(orgid) {
      let res = await getOfficeList({ orgType: 15061007, parentOrgId: orgid });
      let arr = res.data.map(x => ({ text: x.orgName, value: x.orgId }));
      this.topFilterList.find(x => x.fieldName == 'officeId').itemList = arr;
      this.topFilterList.find(x => x.fieldName == 'officeId').initialValue = '';
    },
    async getNotPage(orderType) {
      let list = await getNotPage({ orderType: orderType });
      this.topFilterList.map(x => {
        if (x.fieldName == 'orderDetailType') {
          x.itemList = list.data.map(x => ({ text: x.subName, value: x.subId }));
        }
      });
    },
    selectChangeHandle(row) {
      if (row.length > 0) {
        this.isOpen = false;
        this.selectList = row || [];
      } else {
        this.isOpen = true;
        this.selectList = [];
      }
    },
    seacherFun() {
      this.issearch = true;
    },
    async addHandle(type) {
      if (type == 1) {
        this.addVisible = true;
      } else if (type == 2) {

        let json = Object.assign({}, { CODE: 'CODE_0000033' }, this.fetchParams);
        let res = await exporturl(json);
        if (res.resultCode == 200) {
          this.$router.push('/admin/auth/oem/downloadCenter');
        }



        // this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        //   confirmButtonText: '下载',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // })
        //   .then(() => {
        //     let json = this.fetchParams;
        //     this.exportLoading = true;

        //     exportList(json)
        //       .then(response => {
        //         console.log(response, 'response');
        //         exportExcelFile(response.data, '总部订货单导入');
        //         this.exportLoading = false;
        //       })
        //       .catch(err => {
        //         console.log(err);
        //       });
        //   })
        //   .catch(() => {
        //     console.log('456');
        //     this.$message({
        //       type: 'info',
        //       message: '已取消'
        //     });
        //   });
      } else if (type == 3) {
        this.visible = true;
      } else if (type == 4) {
        await this.$confirm('是否批量提交?', '提示', {
          confirmButtonText: '提交',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            let arr = [];
            this.selectList.map(x => {
              arr.push(x.orderId);
            });
            let json = {
              orderIds: arr
            };
            let res = await subOrderBatch(json);
            if (res.resultCode == 200) {
              this.$notify({
                title: '成功',
                message: '批量提交成功',
                type: 'success'
              });
              this.isOpen = true;
              this.fetchParams = Object.assign({}, this.fetchParams);
            }
          })
          .catch(() => { });
      }else {
        await this.$confirm('是否批量删除?', '提示', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            let arr = [];
            this.selectList.map(x => {
              arr.push(x.orderId);
            });
            let json = {
              orderIds: arr
            };
            let res = await deleteOrderByIds(json);
            if (res.resultCode == 200) {
              this.$notify({
                title: '成功',
                message: '批量删除成功',
                type: 'success'
              });
              this.isOpen = true;
              this.fetchParams = Object.assign({}, this.fetchParams);
            }
          })
          .catch(() => { });
      }
    },
    changeHandle(params) {
      this.isOpen = true;
      this.fetchParams.xhrAbort = false;
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    async editHandle(data, type) {
      if (type == 1) {
        this.formData = data;
        this.emmitVisible = true;
      } else if (type == 2) {
        this.formData = data;
        this.detailVisible = true;
      } else if (type == 3) {
        await this.$confirm('是否进行提报?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            let res = await subOrderById({ orderId: data.orderId });
            if (res.resultCode == 200) {
              this.$notify({
                title: '成功',
                message: '提交成功',
                type: 'success'
              });
              this.isOpen = true;
              this.fetchParams = Object.assign({}, this.fetchParams);
            }
          })
          .catch(() => { });
      } else {
        await this.$confirm('是否确定取消?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            let res = await deleteOrderById({ orderId: data.orderId });
            if (res.resultCode == 200) {
              this.$notify({
                title: '成功',
                message: '取消成功',
                type: 'success'
              });
              this.isOpen = true;
              this.fetchParams = Object.assign({}, this.fetchParams);
            }
          })
          .catch(() => { });
      }
    },
    emitcloseHandler(val) {
      this.emmitVisible = false;
      if (val) {
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    },
    detailCloseHandler() {
      this.detailVisible = false;
    },
    addcloseHandler(val) {
      this.addVisible = false;
      if (val) {
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    },
    resetChange(val) {
      this.isOpen = true;
      this.topFilterList.map(x => {
        if (x.fieldName == 'officeId') {
          x.itemList = [];
        }
        if (x.fieldName == 'orderDetailType') {
          x.itemList = [];
        }
      });
    },
    ownerclose(val, data) {
      if (data) {
        let dealerCodes = [];
        data.map(x => {
          dealerCodes.push(x.dealerCode);
        });
        this.topFilterList.find(x => x.fieldName == 'dealerCode').initialValue = dealerCodes.toString();
      }
      this.issearch = false;
    },
    importcloseHandler(val) {
      this.fetchParams = Object.assign({ xhrAbort: false }, this.fetchParams);
      // this.fetchParams = { ...this.fetchParams }; //刷新
      this.visible = false;
    }
  }
};
</script>
